﻿#region COPYRIGHT
//--------------------------------------------------------------------------------
// <copyright file="CircularBuffer.cs" company="starLiGHT Entertainment Studios">
//    Copyright (c) 2007, 2008, 2009, 2010 
//       Roland Rosenkranz (Glatzemann@email.de)
// </copyright>
// <license>
//   This file is part of starLiGHT.Core.
//
//   starLiGHT.Core is free software: you can redistribute it and/or modify
//   it under the terms of the GNU Lesser General Public License as published by
//   the Free Software Foundation, either version 3 of the License, or
//   (at your option) any later version.
//
//   starLiGHT.Core is distributed in the hope that it will be useful,
//   but WITHOUT ANY WARRANTY; without even the implied warranty of
//   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//   GNU Lesser General Public License for more details.
//
//   You should have received a copy of the GNU Lesser General Public License
//   along with starLiGHT.Core. If not, see http://www.gnu.org/licenses/.
//    
//   ADDITIONAL (commercial) LICENSES for starLiGHT.Core are available on request.
// </license>
// <version>
// **************[ starLiGHT.Engine SVN ]**********************
// * $Rev:: 620                   $:  Revision of last commit *
// * $Author:: unknown            $:  Author of last commit   *
// * $Date:: 2010-12-07 15:23:58 #$:  Date of last commit     *
// ************************************************************
// </version>
//--------------------------------------------------------------------------------
#endregion

namespace starLiGHT.Collections
{
    #region Using Statements
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Text;

    #endregion

    /// <summary>
    /// A circular buffer is a data structure that uses a single, fixed size buffer as if it were connected end-to-end.
    /// If you add more elements to the circular buffer the first element is overwritten in a cyclic manner.
    /// </summary>
    /// <typeparam name="T">The type of the elements stored in the circular buffer</typeparam>
    public class CircularBuffer<T> : IEnumerable<T>
    {
        private T[] buffer;
        private int capacity;
        private int next;
        private int count;
        private int head;
        private int tail;

        /// <summary>
        /// Initializes a new instance of the CircularBuffer class with the given capacity.
        /// </summary>
        /// <param name="capacity">the total size of the circular buffer.</param>
        /// <remarks>
        /// The memory for the elements is immediately allocated in the constructor 
        /// not while adding the elements.
        /// </remarks>
        public CircularBuffer(int capacity)
        {
            this.buffer = new T[capacity];
            this.capacity = capacity;
            this.next = 0;
            this.head = 0;
            this.tail = 0;
            this.count = 0;
        }

        /// <summary>
        /// Gets the total number of actually stored elements in the circular buffer.
        /// </summary>
        public int Count
        {
            get { return this.count; }
        }

        /// <summary>
        /// Gets the capacity of the CircularBuffer. This is the maximum number of unique 
        /// values the buffer can store.
        /// </summary>
        public int Capacity
        {
            get { return this.capacity; }
        }

        public T this[int index]
        {
            get
            {
                while (index > this.capacity)
                {
                    index -= this.capacity;
                }

                while (index < 0)
                {
                    index += this.capacity;
                }

                index += this.head;
                if (index >= this.capacity)
                {
                    index -= this.capacity;
                }

                return this.buffer[index];
            }

            set
            {
                while (index > this.capacity)
                {
                    index -= this.capacity;
                }

                while (index < 0)
                {
                    index += this.capacity;
                }

                index += this.head;
                if (index >= this.capacity)
                {
                    index -= this.capacity;
                }

                this.buffer[index] = value;
            }
        }

        /// <summary>
        /// Initializes the whole circular buffer with the given value
        /// </summary>
        /// <param name="value">the value used to fill the buffer with</param>
        public void Initialize(T value)
        {
            for (int i = 0; i < this.capacity; i++)
            {
                this.Put(value);
            }
        }

        /// <summary>
        /// Clears the elements in the circular buffer.
        /// </summary>
        /// <remarks>
        /// This operation is extremly fast. The elements are still in the buffer after clearing it.
        /// The pointers to the elements and the element count is resetted only.
        /// </remarks>
        public void Clear()
        {
            this.next = 0;
            this.head = 0;
            this.tail = 0;
            this.count = 0;
        }

        /// <summary>
        /// Puts a new value into the circular buffer. It is stored at the actual position. If this element
        /// exceedes the capacity of the buffer, the first added element is overwritten.
        /// </summary>
        /// <param name="value">the value to be stored in the buffer</param>
        public void Put(T value)
        {
            this.buffer[this.next] = value;
            if (this.count < this.capacity)
            {
                this.count++;
                this.tail = this.next;
            }
            else
            {
                if (++this.head == this.capacity)
                {
                    this.head = 0;
                }

                if (++this.tail == this.capacity)
                {
                    this.tail = 0;
                }
            }

            if (++this.next == this.capacity)
            {
                this.next = 0;
            }
        }

        /// <summary>
        /// Gets the element at the given index in the circular buffer.
        /// </summary>
        /// <param name="index">zero based index of the element in the buffer</param>
        /// <returns>the element at the given index.</returns>
        public T Get(int index)
        {
            while (index > this.capacity)
            {
                index -= this.capacity;
            }

            while (index < 0)
            {
                index += this.capacity;
            }

            index += this.head;
            if (index >= this.capacity)
            {
                index -= this.capacity;
            }

            return this.buffer[index];
        }

        public IEnumerator<T> GetEnumerator()
        {
            int nextElement = this.head;
            for (int i = 0; i < this.capacity; i++)
            {
                yield return this.buffer[nextElement];
                if (++nextElement == this.capacity)
                {
                    nextElement = 0;
                }
            }
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            int nextElement = this.head;
            for (int i = 0; i < this.capacity; i++)
            {
                yield return this.buffer[nextElement];
                if (++nextElement == this.capacity)
                {
                    nextElement = 0;
                }
            }
        }
    }
}
